package com.cloudkinto.service.firstvesselorder.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.DicBusinessConstant;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.constant.GlobalConstants;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.exception.BizExceptionI18;
import com.cloudkinto.common.utils.ExcelUtils;
import com.cloudkinto.common.utils.OrderCodeUtil;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.service.fbaproduct.FbaProductService;
import com.cloudkinto.service.fbaproduct.vo.FbaProductDetailRes;
import com.cloudkinto.service.file.FileService;
import com.cloudkinto.service.firstvesselorder.FirstVesselOrderService;
import com.cloudkinto.service.firstvesselorder.vo.*;
import com.cloudkinto.service.storage.StorageService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author zhangyy
 * @since 2020-09-16
 */
@Service
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
public class FirstVesselOrderServiceImpl extends ServiceImpl<FirstVesselOrderDao, FirstVesselOrderDo> implements FirstVesselOrderService {
    private final FirstVesselOrderPackageDao firstVesselOrderPackageDao;
    private final FirstVesselOrderProductDao firstVesselOrderProductDao;
    private final StorageService storageService;
    private final DicBusinessItemDao dicBusinessItemDao;
    private final FbaStorageDao fbaStorageDao;
    private final FileService fileService;
    private final ProductInfoDao productInfoDao;
    private final FbaProductService fbaProductService;
    private final StorageDao storageDao;

    @Override
    public SingleResult addInit() {
        Map result = new HashMap();

        List<Map> storageList = new ArrayList<>();
        LambdaQueryWrapper<StorageDo> storageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        storageDoLambdaQueryWrapper.eq(StorageDo::getCountryType, 2);
        List<StorageDo> storageDos = storageService.getBaseMapper().selectList(storageDoLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(storageDos)) {
            for (StorageDo storageDo : storageDos) {
                Map map = new HashMap();
                map.put("id", storageDo.getId());
                map.put("value", storageDo.getStorageName());
                storageList.add(map);
            }
        }
        result.put("storageList", storageList);

        //运输方式
        List<Map> transportTypeList = new ArrayList<>();
        LambdaQueryWrapper<DicBusinessItemDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.transportType);
        List<DicBusinessItemDo> transportType = dicBusinessItemDao.selectList(wrapper);
        if (!CollectionUtils.isEmpty(transportType)) {
            transportType.forEach(e -> {
                Map map = new HashMap();
                map.put("id", e.getId());
                map.put("value", e.getDicItemValue());
                transportTypeList.add(map);
            });
        }
        result.put("transportTypeList", transportTypeList);

        //状态
        List<Map> statusList = new ArrayList<>();
        LambdaQueryWrapper<DicBusinessItemDo> statusWrapper = new LambdaQueryWrapper<>();
        statusWrapper.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.seaTransportationStatus);
        List<DicBusinessItemDo> statusType = dicBusinessItemDao.selectList(statusWrapper);
        if (!CollectionUtils.isEmpty(statusType)) {
            statusType.forEach(e -> {
                Map map = new HashMap();
                map.put("id", e.getId());
                map.put("value", e.getDicItemValue());
                statusList.add(map);
            });
        }
        result.put("statusList", statusList);

        //fbaStorage
        QueryWrapper wrapper1 = new QueryWrapper();
        wrapper1.orderByAsc("fba_code");
        List<FbaStorageDo> fbaStorageDos = fbaStorageDao.selectList(wrapper1);
        List<Map> fbaStorageList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(fbaStorageDos)) {
            fbaStorageDos.forEach(fbaStorageDo -> {
                Map fbaMap = new HashMap();
                fbaMap.put("id", fbaStorageDo.getId());
                fbaMap.put("code", fbaStorageDo.getFbaCode());
                fbaMap.put("name", fbaStorageDo.getFbaName());
                fbaMap.put("address", fbaStorageDo.getAddress());
                fbaMap.put("postCode", fbaStorageDo.getPostCode());
                fbaMap.put("tel", fbaStorageDo.getTelPhone());
                fbaStorageList.add(fbaMap);
            });
        }
        result.put("fbaStorageList", fbaStorageList);

        //报关方式
        List<Map> customsTypeList = new ArrayList<>();
        Map map = new HashMap();
        map.put("id", 1);
        map.put("value", "退税报关");
        customsTypeList.add(map);
        map = new HashMap();
        map.put("id", 2);
        map.put("value", "非退税");
        customsTypeList.add(map);
        result.put("customsTypeList", customsTypeList);

        //配送方式
        List<Map> distributionTypeList = new ArrayList<>();
        map = new HashMap();
        map.put("id", 1);
        map.put("value", "上门取件");
        distributionTypeList.add(map);
        map = new HashMap();
        map.put("id", 2);
        map.put("value", "送货到仓");
        distributionTypeList.add(map);
        result.put("distributionTypeList", distributionTypeList);


        return SingleResult.success(result);
    }

    @Override
    public FirstVesselOrderAddReq add(FirstVesselOrderAddReq req, Long userId, Long companyId) {
        addCheck(req);
        FirstVesselOrderDo entityDo = new FirstVesselOrderDo();
        fileService.uploadFile(req.getCommodityFileId());
        fileService.uploadFile(req.getCustomsClearanceFileId());
        fileService.uploadFile(req.getDeclarationInformationFileId());
        BeanUtils.copyProperties(req, entityDo);
        entityDo.setCompanyId(companyId);
        entityDo.setPickDate(TimeUtils.parseDate(req.getPickDate()));
        entityDo.setDeliverTime(TimeUtils.parseDate(req.getDeliverTime()));
        entityDo.setIsLabelling(SysConstant.DELETE_FLAG_FALSE);
        entityDo.setResultStatus(getResultStatus(req.getStatus()));
        handlerAddBefore(entityDo, userId);
        baseMapper.insert(entityDo);
        String firstVesselNumber = OrderCodeUtil.getFirstVesselNumber(entityDo.getId());
        entityDo.setOrderNumber(firstVesselNumber);
        baseMapper.updateById(entityDo);

        req.getPackageList().forEach(packageReq -> {
            FirstVesselOrderPackageDo packageDo = new FirstVesselOrderPackageDo();
            BeanUtils.copyProperties(packageReq, packageDo);
            packageDo.setOrderId(entityDo.getId());
            packageDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
            firstVesselOrderPackageDao.insert(packageDo);

            packageReq.getProductList().forEach(productReq -> {
                FirstVesselOrderProductDo productDo = new FirstVesselOrderProductDo();
                BeanUtils.copyProperties(productReq, productDo);
                productDo.setOrderId(entityDo.getId());
                productDo.setPackageId(packageDo.getId());
                productDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
                firstVesselOrderProductDao.insert(productDo);
            });
        });


        return req;
    }

    /**
     * 根据status 获取resultStatus
     */
    private Integer getResultStatus(Long status) {
        Integer resultStatus = null;
        if (status >= DicBusinessItemConstant.seaSubmit && status <= DicBusinessItemConstant.seaDispatchShip) {
            resultStatus = 1;
        } else if (status.equals(DicBusinessItemConstant.seaDelivery)) {
            resultStatus = 2;
        } else if (status.equals(DicBusinessItemConstant.seaBack)) {
            resultStatus = 3;
        }
        return resultStatus;
    }

    /**
     * 新增校验
     */
    private void addCheck(FirstVesselOrderAddReq req) {
        if (req.getIsCloudkintoExport() == 1 && StringUtils.isBlank(req.getDutyParagraph())) {
            throw new BizExceptionI18("input.clear.title");
        }
    }

    /**
     * 做新增之前要执行的业务定制处理
     */
    private void handlerAddBefore(FirstVesselOrderDo entityDo, Long userId) {
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }


    @Override
    public SingleResult updateInit(Long id) {
        Map result = (Map) addInit().getData();
        result.put("detail", detail(id));
        return SingleResult.success(result);
    }

    @Override
    public FirstVesselOrderUpdateReq update(FirstVesselOrderUpdateReq req, Long userId) {
        FirstVesselOrderDo entityDo = baseMapper.selectById(req.getId());

        if (req.getCommodityFileId() != null && !req.getCommodityFileId().equals(entityDo.getCommodityFileId())) {
            fileService.deleteFile(entityDo.getCommodityFileId());
            fileService.uploadFile2(req.getCommodityFileId(), entityDo.getCommodityFileId());
        }
        if (req.getCustomsClearanceFileId() != null && !req.getCustomsClearanceFileId().equals(entityDo.getCustomsClearanceFileId())) {
            fileService.deleteFile(entityDo.getCustomsClearanceFileId());
            fileService.uploadFile2(req.getCustomsClearanceFileId(), entityDo.getCustomsClearanceFileId());
        }
        if (req.getDeclarationInformationFileId() != null && !req.getDeclarationInformationFileId().equals(entityDo.getDeclarationInformationFileId())) {
            fileService.deleteFile(entityDo.getDeclarationInformationFileId());
            fileService.uploadFile2(req.getDeclarationInformationFileId(), entityDo.getDeclarationInformationFileId());
        }
        if (entityDo.getStatus().equals(DicBusinessItemConstant.seaUnsubmit)) {
            req.setStatus(DicBusinessItemConstant.seaSubmit);
            entityDo.setStatus(DicBusinessItemConstant.seaSubmit);
        }

        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);


        baseMapper.updateById(entityDo);

        LambdaQueryWrapper<FirstVesselOrderPackageDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        packageDoLambdaQueryWrapper.eq(FirstVesselOrderPackageDo::getOrderId, req.getId());
        firstVesselOrderPackageDao.delete(packageDoLambdaQueryWrapper);

        LambdaQueryWrapper<FirstVesselOrderProductDo> productDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        productDoLambdaQueryWrapper.eq(FirstVesselOrderProductDo::getOrderId, req.getId());
        firstVesselOrderProductDao.delete(productDoLambdaQueryWrapper);

        req.getPackageList().forEach(packageReq -> {
            FirstVesselOrderPackageDo packageDo = new FirstVesselOrderPackageDo();
            BeanUtils.copyProperties(packageReq, packageDo);
            packageDo.setOrderId(entityDo.getId());
            packageDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
            firstVesselOrderPackageDao.insert(packageDo);

            packageReq.getProductList().forEach(productReq -> {
                FirstVesselOrderProductDo productDo = new FirstVesselOrderProductDo();
                BeanUtils.copyProperties(productReq, productDo);
                productDo.setOrderId(entityDo.getId());
                productDo.setPackageId(packageDo.getId());
                productDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
                firstVesselOrderProductDao.insert(productDo);
            });
        });

        return req;
    }

    @Override
    public void uploadCartonabel(FirstVesselUploadCartonabelReq req, Long userId) {
        FirstVesselOrderDo entityDo = baseMapper.selectById(req.getId());
        if (req.getCommodityFileId() != null) {
            fileService.deleteFile(entityDo.getCommodityFileId());
            fileService.uploadFile2(req.getCommodityFileId(), entityDo.getCommodityFileId());
        }
    }

    /**
     * 编辑校验
     */
    private void updateCheck(Object req) {

    }

    /**
     * 做修改之前要执行的业务定制处理
     */
    private void handlerUpdateBefore(FirstVesselOrderDo entityDo, Long userId) {
        entityDo.setUpdateBy(userId);
        entityDo.setUpdateTime(new Date());
    }


    @Override
    public int delete(Long id, Long userId) {
        FirstVesselOrderDo entityDo = baseMapper.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        baseMapper.deleteById(id);

        LambdaQueryWrapper<FirstVesselOrderPackageDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        packageDoLambdaQueryWrapper.eq(FirstVesselOrderPackageDo::getOrderId, entityDo.getId());
        firstVesselOrderPackageDao.delete(packageDoLambdaQueryWrapper);

        LambdaQueryWrapper<FirstVesselOrderProductDo> productDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        productDoLambdaQueryWrapper.eq(FirstVesselOrderProductDo::getOrderId, entityDo.getId());
        firstVesselOrderProductDao.delete(productDoLambdaQueryWrapper);

        fileService.deleteFile(entityDo.getCommodityFileId());
        fileService.deleteFile(entityDo.getDeclarationInformationFileId());
        fileService.deleteFile(entityDo.getCustomsClearanceFileId());
        return 1;
    }

    /**
     * 做删除之前要执行的业务定制处理
     */
    private void handlerDeleteBefore(FirstVesselOrderDo entityDo, Long userId) {
        entityDo.setDeleteBy(userId);
        entityDo.setDeleteTime(new Date());
    }

    @Override
    public FirstVesselOrderDetailRes detail(Long id) {
        FirstVesselOrderDo entityDo = baseMapper.selectById(id);
        FirstVesselOrderDetailRes res = new FirstVesselOrderDetailRes();
        if (Objects.isNull(entityDo)) {
            throw new BizExceptionI18("no.order.info");
        }
        BeanUtils.copyProperties(entityDo, res);
        res.setCustomsClearanceFileUrl(fileService.getFilePath(entityDo.getCustomsClearanceFileId()));
        res.setDeclarationInformationFileUrl(fileService.getFilePath(entityDo.getDeclarationInformationFileId()));
        res.setCommodityFileUrl(fileService.getFilePath(entityDo.getCommodityFileId()));
        res.setDeclarationCertificateFileUrl(fileService.getFilePath(entityDo.getDeclarationCertificateFileId()));

        DicBusinessItemDo businessItemDo = dicBusinessItemDao.selectById(entityDo.getStatus());
        if (businessItemDo != null) {
            res.setStatus(businessItemDo.getDicItemValue());
        }
        res.setResultStatus(getResultStatusStr(entityDo.getResultStatus()));

        StorageDo storageDo = storageDao.selectById(entityDo.getStorageId());
        if (storageDo != null) {
            res.setStorageName(storageDo.getStorageName());
        }

        FbaStorageDo fbaStorageDo = fbaStorageDao.selectById(entityDo.getFbaStorageId());
        if (fbaStorageDo != null) {
            res.setFbaStorageName(fbaStorageDo.getFbaName());
        }

        DicBusinessItemDo logisticsType = dicBusinessItemDao.selectById(entityDo.getLogisticsType());
        if (logisticsType != null) {
            res.setLogisticsTypeName(logisticsType.getDicItemValue());
        }

        res.setIsCloudkintoExportName(entityDo.getIsCloudkintoExport() == 1 ? "是" : "否");
        res.setCustomsTypeName(entityDo.getCustomsType() == 1 ? "报关退税" : "非退税");
        res.setIsPurchaseOfInsuranceName(entityDo.getIsPurchaseOfInsurance() == 1 ? "是" : "否");
        res.setDistributionTypeName(entityDo.getDistributionType() == 1 ? "上门取件" : "送货到仓");

        List<FirstVesselOrderPackageDetailRes> packageDetailResList = new ArrayList<>();

        LambdaQueryWrapper<FirstVesselOrderPackageDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        packageDoLambdaQueryWrapper.eq(FirstVesselOrderPackageDo::getOrderId, id);
        List<FirstVesselOrderPackageDo> firstVesselOrderPackageDos = firstVesselOrderPackageDao.selectList(packageDoLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(firstVesselOrderPackageDos)) {
            firstVesselOrderPackageDos.forEach(packageDo -> {
                FirstVesselOrderPackageDetailRes packageDetailRes = new FirstVesselOrderPackageDetailRes();
                BeanUtils.copyProperties(packageDo, packageDetailRes);
                packageDetailRes.setWeight(packageDo.getWeight() * packageDo.getCount());

                List<FbaProductDetailRes> productDetailResList = new ArrayList<>();
                LambdaQueryWrapper<FirstVesselOrderProductDo> productDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                productDoLambdaQueryWrapper.eq(FirstVesselOrderProductDo::getPackageId, packageDo.getId());
                List<FirstVesselOrderProductDo> firstVesselOrderProductDos = firstVesselOrderProductDao.selectList(productDoLambdaQueryWrapper);
                if (!CollectionUtils.isEmpty(firstVesselOrderProductDos)) {
                    firstVesselOrderProductDos.forEach(productDo -> {
                        FbaProductDetailRes productDetailRes = fbaProductService.detail(productDo.getProductId());
//                        BeanUtils.copyProperties(productDo,productDetailRes);
//                        ProductInfoDo productInfoDo = productInfoDao.selectById(productDo.getProductId());
//                        if(productInfoDo != null){
//                            productDetailRes.setProductName(productInfoDo.getProductName());
//                        }
                        productDetailRes.setCount(productDo.getCount());
                        productDetailResList.add(productDetailRes);
                    });
                }

                packageDetailRes.setProductList(productDetailResList);
                packageDetailResList.add(packageDetailRes);
            });
        }
        res.setPackageList(packageDetailResList);
        return res;
    }

    private String getResultStatusStr(Integer resultStatus) {
        if (resultStatus == null) {
            return "";
        }
        if (resultStatus == 1) {
            return "当前订单";
        } else if (resultStatus == 2) {
            return "已完成";
        } else if (resultStatus == 3) {
            return "已退回";
        }
        return "";
    }


    @Override
    public SingleResult pageInit() {
        return SingleResult.success("");
    }

    @Override
    public List<FirstVesselOrderPageRes> getList(Map<String, String> map) {
        QueryWrapper<FirstVesselOrderDo> wrapper = queryBuild(map);
        List<FirstVesselOrderDo> list = this.list(wrapper);
        List<FirstVesselOrderPageRes> result = handlerListAfter(list);
        return result;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<FirstVesselOrderDo> wrapper = queryBuild(map);
        IPage<FirstVesselOrderDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<FirstVesselOrderPageRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        result.setMapInfo(census(map));
        return result;
    }

    @Override
    public List<FirstVesselExcelImportPackageRes> importExcel(MultipartFile file) throws IOException {
        if (file == null) {
            throw new BizException("no.file");
        }
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!GlobalConstants.IMG_TYPE_XLS.equals(suffix.toUpperCase()) &&
                !GlobalConstants.IMG_TYPE_XLSX.equals(suffix.toUpperCase())) {
            throw new BizExceptionI18("error.charge.type");
        }
        List<FIrstVesselExcelImportVo> excelImportVoList = ExcelUtils.importExcel(file, 0, 1, FIrstVesselExcelImportVo.class);
        List<FirstVesselExcelImportPackageRes> packageList = new ArrayList<>();
        Map<Long, List<FIrstVesselExcelImportVo>> map = excelImportVoList.stream().filter(product -> StringUtils.isNotBlank(product.getCommoditySku())).collect(Collectors.groupingBy(FIrstVesselExcelImportVo::getPackageNo));
        if (!CollectionUtils.isEmpty(map)) {
            for (Long packageNo : map.keySet()) {
                List<FIrstVesselExcelImportVo> excelImportVos = map.get(packageNo);
                if (!CollectionUtils.isEmpty(excelImportVos)) {
                    FirstVesselExcelImportPackageRes packageAdd = new FirstVesselExcelImportPackageRes();
                    packageAdd.setHeight(excelImportVos.get(0).getHeight().floatValue());
                    packageAdd.setLenght(excelImportVos.get(0).getLength().floatValue());
                    packageAdd.setWidth(excelImportVos.get(0).getWidth().floatValue());
                    packageAdd.setWeight(excelImportVos.get(0).getWeight().floatValue());
                    packageAdd.setCunt(excelImportVos.get(0).getPackageCount());
                    packageAdd.setPoNumber(excelImportVos.get(0).getPoNumber());
                    packageAdd.setUpcNumber(excelImportVos.get(0).getUpcNumber());
                    packageAdd.setTips(excelImportVos.get(0).getTips());

                    List<JSONObject> productAddList = new ArrayList<>();
                    for (FIrstVesselExcelImportVo excelImportVo : excelImportVos) {
                        //商品
                        JSONObject productAdd = new JSONObject();
                        LambdaQueryWrapper<ProductInfoDo> wrapper = new LambdaQueryWrapper<>();
                        wrapper.eq(ProductInfoDo::getCommoditySku, excelImportVo.getCommoditySku());
                        ProductInfoDo productInfoDo = productInfoDao.selectOne(wrapper);
                        if (productInfoDo != null) {
                            productAdd.put("productId", productInfoDo.getId());
                            productAdd.put("commoditySku", productInfoDo.getCommoditySku());
                            productAdd.put("productName", productInfoDo.getCommodityName());
                            productAdd.put("createTime", productInfoDo.getCreateTime());
                        } else {
                            productAdd.put("productId", "");
                            productAdd.put("commoditySku", "产品不存在，请检查SKU");
                            productAdd.put("productName", "");
                            productAdd.put("createTime", "");
                        }
                        productAdd.put("count", excelImportVo.getCount());

                        productAddList.add(productAdd);
                    }

                    packageAdd.setProductDetailList(productAddList);

                    packageList.add(packageAdd);
                }
            }
        }

        return packageList;
    }

    //统计信息
    private Map census(Map<String, String> queryMap) {

        List<Map> result = new ArrayList<>();

        Map mapTotal = new HashMap();
        queryMap.remove("status");
        int total = baseMapper.selectCount(queryBuild(queryMap));
        mapTotal.put("count", total);
        mapTotal.put("name", "全部");
        result.add(mapTotal);


        LambdaQueryWrapper<DicBusinessItemDo> businessItemDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        businessItemDoLambdaQueryWrapper.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.seaTransportationStatus);
        List<DicBusinessItemDo> businessItemDoList = dicBusinessItemDao.selectList(businessItemDoLambdaQueryWrapper);

        if (!CollectionUtils.isEmpty(businessItemDoList)) {
            for (DicBusinessItemDo itemDo : businessItemDoList) {
                queryMap.put("status", itemDo.getId() + "");
                Map map = new HashMap();
                int count = baseMapper.selectCount(queryBuild(queryMap));
                map.put("count", count);
                map.put("name", itemDo.getDicItemValue());
                map.put("id", itemDo.getId());
                result.add(map);
            }
        }


        Map map = new HashMap();
        map.put("census", result);
//        List<Map> result = new ArrayList<>();
//        Map mapTotal = new HashMap();
//        wrapper.remove("status");
//        int total = dao.selectCount(queryBuild(wrapper));
//        mapTotal.put("count", total);
//        mapTotal.put("name", "全部");
////        mapTotal.put("id", null);
//        result.add(mapTotal);
//
//
//        Map status = new HashMap();
//        QueryWrapper<FirstVesselOrderDo> firstVesselOrderDoQueryWrapper = queryBuild(wrapper);
//        firstVesselOrderDoQueryWrapper.eq("result_status", 1);
//        int current = dao.selectCount(firstVesselOrderDoQueryWrapper);
//        status.put("count", current);
//        status.put("name", "当前订单");
//        status.put("id", 1);
//        result.add(status);
//
//        status = new HashMap();
//        firstVesselOrderDoQueryWrapper = queryBuild(wrapper);
//        firstVesselOrderDoQueryWrapper.eq("result_status", 2);
//        int finish = dao.selectCount(firstVesselOrderDoQueryWrapper);P
//        status.put("count", finish);
//        status.put("name", "已完成");
//        status.put("id", 2);
//        result.add(status);
//
//        status = new HashMap();
//        firstVesselOrderDoQueryWrapper = queryBuild(wrapper);
//        firstVesselOrderDoQueryWrapper.eq("result_status", 3);
//        int back = dao.selectCount(firstVesselOrderDoQueryWrapper);
//        status.put("count", back);
//        status.put("name", "已退回");
//        status.put("id", 3);
//        result.add(status);
//
//        Map map = new HashMap();
//        map.put("census", result);
        return map;
    }

    //查询分页列表之后对列表数据的处理
    private List<FirstVesselOrderPageRes> handlerListAfter(List<FirstVesselOrderDo> list) {
        List<FirstVesselOrderPageRes> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(firstVesselOrderDo -> {
                FirstVesselOrderPageRes res = new FirstVesselOrderPageRes();
                res.setId(firstVesselOrderDo.getId());
                res.setOrderNumber(firstVesselOrderDo.getOrderNumber());
                res.setRemark(firstVesselOrderDo.getRemark());
                res.setCreateTime(firstVesselOrderDo.getCreateTime());
                res.setResultStatus(getResultStatusStr(firstVesselOrderDo.getResultStatus()));
                StorageDo storageDo = storageService.getBaseMapper().selectById(firstVesselOrderDo.getStorageId());
                if (storageDo != null) {
                    res.setStorage(storageDo.getStorageName());
                }
                FbaStorageDo fbaStorageDo = fbaStorageDao.selectById(firstVesselOrderDo.getFbaStorageId());
                if (fbaStorageDo != null) {
                    res.setFbaStorage(fbaStorageDo.getFbaCode() + fbaStorageDo.getFbaName());
                }
                DicBusinessItemDo businessItemDo = dicBusinessItemDao.selectById(firstVesselOrderDo.getStatus());
                if (businessItemDo != null) {
                    res.setStatus(businessItemDo.getDicItemValue());
                }

                LambdaQueryWrapper<FirstVesselOrderPackageDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                packageDoLambdaQueryWrapper.eq(FirstVesselOrderPackageDo::getOrderId, firstVesselOrderDo.getId());
                List<FirstVesselOrderPackageDo> firstVesselOrderPackageDos = firstVesselOrderPackageDao.selectList(packageDoLambdaQueryWrapper);
                int packageCount = 0;
                double volume = 0;
                if (!CollectionUtils.isEmpty(firstVesselOrderPackageDos)) {
                    for (FirstVesselOrderPackageDo packageDo : firstVesselOrderPackageDos) {
                        packageCount += packageDo.getCount();
                        volume += packageDo.getLength() * packageDo.getWidth() * packageDo.getHeight() / 1000000;
                    }
                }
                res.setVolume(new BigDecimal(volume).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                res.setPackageCounts(packageCount);

                if (firstVesselOrderDo.getStatus().equals(DicBusinessItemConstant.seaUnsubmit)) {
                    res.setIsEdit(1);
                } else {
                    res.setIsEdit(2);
                }

                result.add(res);
            });
        }
        return result;
    }

    private IPage<FirstVesselOrderDo> pageInit(Map<String, String> map) {
        IPage<FirstVesselOrderDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<FirstVesselOrderDo> queryBuild(Map<String, String> map) {
        QueryWrapper<FirstVesselOrderDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.like("order_number", map.get("keyword"));
        }
        if (StringUtils.isNotBlank(map.get("status"))) {
            wrapper.eq("status", map.get("status"));
        }
        if (StringUtils.isNotBlank(map.get("companyId"))) {
            wrapper.eq("company_id", map.get("companyId"));
        }
        if (StringUtils.isNotBlank(map.get("startDate"))) {
            wrapper.ge("create_time", map.get("startDate"));
        }
        if (StringUtils.isNotBlank(map.get("endDate"))) {
            wrapper.le("create_time", map.get("endDate"));
        }


        return wrapper.orderByDesc("id");
    }


}
